//
//  CityTourPlay.m
//  ImGuider
//
//  Created by 王鹏宇 on 2017/6/2.
//  Copyright © 2017年 imguider. All rights reserved.
//

#import "CityTourPlay.h"
#import "PlayBar.h"

#import "SDCycleScrollView.h"
#import "StarRateView.h"
#import "DownloadListDAO.h"
#import "RatingVC.h"
#import "CityTourLinePointCell.h"
#import "TransportHeaderView.h"

#import "IGAnnotation.h"
#import "SpotAnnView.h"
#import "UserSubmitQustionVC.h"
#import "MKMapView+ZoomLevel.h"
#import "ScenicDescribeVC.h"
#define PopViewH   60
@interface CityTourPlay () <SpotAnnViewDelegate,UIScrollViewDelegate,playBarDelegate,MKMapViewDelegate,UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout>

@property (weak, nonatomic) IBOutlet MKMapView *mapView;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *toBottomSpace;


@property (nonatomic, strong) PlayBar *playBar;

@property (nonatomic, strong) SDCycleScrollView *cycleScrollView;

@property (nonatomic, strong) StarRateView *starView;

@property (nonatomic, strong) UIView *popView;

@property (nonatomic, strong) UICollectionView *lineCollectionView;

@property (nonatomic, strong) UIButton *upOrDownBtn;
@property (nonatomic, strong) UIButton *guideBtn;
@property (nonatomic, strong) UIButton *currentLocationBtn;


@property (nonatomic, strong) UILabel *startOrEndLabel;
@property (nonatomic, strong) UILabel *scenicPointLabel;
@property (nonatomic, strong) UILabel *starCountLabel;

@property (nonatomic, strong) UIImageView *startOrEndBg;

@property (nonatomic, strong) NSArray *viewsArray;
@property (nonatomic, strong) NSArray *annArray;

@property (nonatomic, strong) NSTimer *timer;
@property (nonatomic, strong) NSTimer *autoPalytimer;

@property (nonatomic) CGPoint Contentoffset;
@property (nonatomic) CGFloat lastDistance;
@property (nonatomic) NSInteger currentIndex;

@property (nonatomic) BOOL isSuspend;
@property (nonatomic) BOOL hasDrawedLine;
@property (nonatomic) BOOL needScroll;

@property (nonatomic) long long alertTime;// 记录上次提醒时间，播放时每3分钟提醒一次

@end

@implementation CityTourPlay

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeState:) name:kDownloadCompleteDownNotif object:nil];
    
    [self setupUI];
    [self setUpPlayBar];
    [self popView];
    [self initCityTourFunctionItemView];
    [self setupData];
}
- (void)dealloc {
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    
    [_mapView removeAnnotations:self.annArray];
    
    [_mapView removeFromSuperview];
    _mapView = nil;
    
    [_timer invalidate];
    _timer = nil;
    
    [MobClick event:@"4_1_1"];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [MobClick beginLogPageView:@"4"];
    
    [self startTimer];
}

- (void)viewWillDisappear:(BOOL)animated {
    
    [super viewWillDisappear:animated];
    
    if (!self.isStraightPlay) {
        [[IGAvPlayerManager shareManeger] stop];
    }
    [MobClick endLogPageView:@"4"];
    
    [self stopTimer];
}

- (void)setupUI {
    
    self.barBGAlpha = 0;
    [self setNavGradient];
    self.currentIndex = -1;
    if (ISiPhoneX) {
        self.toBottomSpace.constant = 94;
    }
}

- (void)startTimer {
    
    [self stopTimer];
    
    self.timer = [NSTimer scheduledTimerWithTimeInterval:30.0 target:self selector:@selector(timerDrawLine) userInfo:nil repeats:YES];
    [[NSRunLoop mainRunLoop]addTimer:self.timer forMode:NSDefaultRunLoopMode];
    
    self.autoPalytimer = [NSTimer scheduledTimerWithTimeInterval:10.0 target:self selector:@selector(autoPalytimerPlay) userInfo:nil repeats:YES];
    [[NSRunLoop mainRunLoop]addTimer:self.autoPalytimer forMode:NSDefaultRunLoopMode];
}

- (void)stopTimer {
    
    [self.timer invalidate];
    self.timer = nil;
    
    [self.autoPalytimer invalidate];
    self.autoPalytimer = nil;
}

- (void)autoPalytimerPlay {
    
    IGLog(@"--------第一个autoPalytimer");
    
    if (![AppManager sharedManager].automaticPlay) {
        
        return;
    }
    
    CLLocationCoordinate2D selfCoor = self.mapView.userLocation.coordinate;
    
    for (int i = 0; i < self.annArray.count ; i ++) {
        
        IGAnnotation *ann = self.annArray[i];
        
        BOOL autoplay = [ann.infos[IGAnnotationAutoPlayKey] boolValue];
        BOOL hasNav = ann.hasNav;
        if (autoplay && !hasNav) {
            
            CGFloat distance = [IGUtils getDistanceFromCoordinate:selfCoor toCoordinate:ann.coordinate];
            
            CGFloat autoRange = [ann.infos[IGAnnotationAutoRangeKey] floatValue];
            
            if (autoRange <= 1) {
                continue;
            }
            
            if (distance <= autoRange) {
                
                ann.hasNav = YES;
                
                if ([IGAvPlayerManager shareManeger].isPlay) {
                    
                    long long nowTime = [[NSDate date] timeIntervalSince1970];
                    
                    long long minsDifferenr = nowTime - self.alertTime;
                    
                    if (minsDifferenr > 180) {
                        
                        self.alertTime = nowTime;
                        
                        [IGAlertView alertWithTitle:@"" message:[NSString localizedStringWithFormat:MYLocalizedString(@"CITYTOUR_EXHANGE_ALERT", nil),ann.title,ann.title] cancelButtonTitle:MYLocalizedString(@"PUBLIC_CANCEL", nil) commitBtn:MYLocalizedString(@"PUBLIC_SWITCH", nil) commit:^{
                            
                            [self playAndChangeSpotAnnViewWith:i needPlay:YES];
                        } cancel:nil];
                        
                    }
                    
                } else {
                    
                    self.alertTime = 0;
                    
                    
                    
                    if ([[IGAvPlayerManager shareManeger].currentURL isEqualToString:ann.infos[IGAnnotationPlaypathKey]]) {
                        
                        [[IGAvPlayerManager shareManeger] resetPlayMusic];
                        
                    } else {
                        
                        [self playAndChangeSpotAnnViewWith:i needPlay:YES];
                    }
                }
                
                break;
            }
        }
    }
}

- (void)timerDrawLine {
    
    IGLog(@"--------第二个timerDrawLine");
    
    if (!self.hasDrawedLine) {
        
        return;
    }
    
    if (self.annArray.count > self.currentIndex) {
        
        IGAnnotation *ann = self.annArray[self.currentIndex];
        [self addLineTo:ann.coordinate];
    }
}

//- (UIButton *)submitQuestionBtn {
//
//    if (!_submitQuestionBtn) {
//
//        _submitQuestionBtn = [UIButton buttonWithType:UIButtonTypeCustom];
//
//        _submitQuestionBtn.frame = CGRectMake(SCREEN_WIDTH - 53, SCREEN_HEIGHT - 195, 45, 45);
//        [_submitQuestionBtn setImage:[UIImage imageNamed:@"问行家"] forState:UIControlStateNormal];
//        [_submitQuestionBtn addTarget:self action:@selector(submitQuestion:) forControlEvents:UIControlEventTouchUpInside];
//    }
//
//    return _submitQuestionBtn;
//}

- (void)setUpPlayBar {
    
    _playBar = [PlayBar shareManeger];
    _playBar.delegate = self;
    _playBar.type = 1;
    [self.view addSubview:_playBar];
    @weakify(self);
    [_playBar mas_makeConstraints:^(MASConstraintMaker *make) {
        
        @strongify(self);
        make.leading.equalTo(self.view.mas_leading);
        make.trailing.equalTo(self.view.mas_trailing);
        make.top.equalTo(self.mapView.mas_bottom);
        make.height.mas_equalTo(60);
    }];
}


- (void)changeState:(NSNotification *)notif {
    
    if (self.isSuspend) {
        return;
    }
    
    dispatch_async(dispatch_get_main_queue(), ^ {
        
        NSString *lineID = notif.userInfo[kDownloadNotifLineID];
        
        if (![lineID isEqualToString:self.lineModel.unionid]) {
            return;
        }
        
        
        CGFloat progress;
        DownloadState state = [[DownloadManager sharedManager] downloadSateForModel:self.lineModel progress:&progress];
        
        self.lineModel.progress = progress;
        self.lineModel.state = state;
        
        self.playBar.downloadState = state;
        self.playBar.downloadProgress = progress;
    });
}

- (void)downloadStart {
    
    [MobClick event:@"4_0_11"];
    self.isSuspend = NO;
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        BOOL hasDownload = [[NSUserDefaults standardUserDefaults] boolForKey:self.lineModel.unionid];
        
        if (!hasDownload) {
            dispatch_async(dispatch_get_main_queue(), ^ {
                [IGUtils showToast:MYLocalizedString(@"SITEPLAY_DOWNLOADTIP", nil)];
            });
            [[NSUserDefaults standardUserDefaults] setBool:YES forKey:self.lineModel.unionid];
            [[NSUserDefaults standardUserDefaults] synchronize];
            
        }
        
    });
    
    CGFloat progress;
    DownloadState state = [[DownloadManager sharedManager] downloadSateForModel:self.lineModel progress:&progress];
    
    self.lineModel.progress = progress;
    self.lineModel.state = state;
    
    self.playBar.downloadState= state;
    self.playBar.downloadProgress = progress;
    
    [[DownloadManager sharedManager] addDownloadWithLineModel:self.lineModel];
}

- (void)downloadSuspend {
    
    [[DownloadManager sharedManager] pauseWithLineModel:self.lineModel];
    self.isSuspend = YES;
}

//使用addLineFrom方法添加导航路线
- (void)addLineTo:(CLLocationCoordinate2D)toCoordinate {
    
    self.hasDrawedLine = YES;
    
    MKDirectionsRequest *request = [[MKDirectionsRequest alloc]init];
    
    CLLocationCoordinate2D coorself = self.mapView.userLocation.coordinate;
    
    if (coorself.latitude == 0 && coorself.longitude == 0) {

        coorself = transformFromWGSToGCJ([LocationManager sharedManager].currentLocation.coordinate, self.lineModel.country);
    }
    
    CGFloat distance = [IGUtils getDistanceFromCoordinate:self.mapView.userLocation.coordinate toCoordinate:toCoordinate];
    
    if (distance < 10) {
        [self.mapView removeOverlays:self.mapView.overlays];
        return;
    }
    
    IGLog(@"----总共coorsel%f---%f",coorself.latitude,coorself.longitude);
    IGLog(@"----总共coorto%f---%f",toCoordinate.latitude,toCoordinate.longitude);
    
    MKPlacemark *fromPm = [[MKPlacemark alloc] initWithCoordinate:coorself addressDictionary:nil];
    
    request.source = [[MKMapItem alloc]initWithPlacemark:fromPm];
    
    //设置终点
    MKPlacemark *toPm = [[MKPlacemark alloc] initWithCoordinate:toCoordinate addressDictionary:nil];
    
    request.destination = [[MKMapItem alloc]initWithPlacemark:toPm];
    request.requestsAlternateRoutes = YES;
    request.transportType = MKDirectionsTransportTypeWalking;//步行模式
    
    //方向对象
    MKDirections *directions = [[MKDirections alloc]initWithRequest:request];
    
    //计算路线
    [directions calculateDirectionsWithCompletionHandler:^(MKDirectionsResponse * _Nullable response, NSError * _Nullable error) {
        
        IGLog(@"----总共结果coorto%f---%f",toCoordinate.latitude,toCoordinate.longitude);
        
        [self.mapView removeOverlays:self.mapView.overlays];
        
        if (response.routes.count > 0) {
            
            [self.mapView addOverlay:response.routes.firstObject.polyline];
        } else if (error) {
            
            [IGUtils showToast:[IGUtils tipFromError:error]];
        } else {
            
            [IGUtils showToast:MYLocalizedString(@"PUBLIC_NETWORK_TIMEOUT", nil)];
        }
    }];
}


- (void)setupData {
    
    if (self.pageType == 1 || self.pageType == 2) {
        
        if (self.lineModel.hasscore.integerValue > 0) {
            [self.commentBtn setTitle:MYLocalizedString(@"SITEPLAY_COMMENT", nil) forState:UIControlStateNormal];
        }
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self loadDataSource];
        });
        return;
    }
    
    [ActivityIndicatorView showHUDAddedTo:self.view backgroundColor:[UIColor whiteColor]];
    @weakify(self);
    [NetAPIManager getLineDetailWithLinID:self.lineID block:^(LineModel *model, NSError *error) {
        
        @strongify(self);
        [ActivityIndicatorView hideHUDAddedTo:self.view];
        
        self.lineModel = model;
        
        [self loadDataSource];
    }];
}

- (void)loadDataSource {
    
    // 获取地图上所有的大头针数据模型
    
    if (self.lineModel.records.count == 0) {
        return;
    }
    
    NSMutableArray *annArray = [NSMutableArray array];
    NSMutableArray *viewsArray = [NSMutableArray array];
    
    
    NSInteger index = 0;
    for (ScenicPoint *point in self.lineModel.records) {
        
        if (point == self.lineModel.records.firstObject) {
            continue;
        }
        
        [viewsArray addObject:point];
        
        IGAnnotation *annotation = [[IGAnnotation alloc]init];
        
        CLLocationCoordinate2D location = CLLocationCoordinate2DMake(point.lat.doubleValue, point.lng.doubleValue);
        
        annotation.coordinate = transformFromWGSToGCJ(location, self.lineModel.country);
        
        NSDictionary *dict = @{IGAnnotationNumberKey:point.number,IGAnnotationImageKey:point.pictureArray.firstObject,IGAnnotationIndexKey:@(index), IGAnnotationAutoPlayKey:@(point.canplay), IGAnnotationAutoRangeKey:@(point.autoplayrange), IGAnnotationPlaypathKey : point.playpath ? point.playpath : @""};
        
        annotation.infos = dict;
        annotation.title = point.spotname;
        
        [annArray addObject:annotation];
        
        if (index == 0) {
            [self.mapView setCenterCoordinate:annotation.coordinate zoomLevel:kZoomLevel animated:NO];
        }
        index ++;
    }
    self.viewsArray = viewsArray;
    self.annArray = annArray;
    
    [self.mapView addAnnotations:annArray];
    
    [self.lineCollectionView reloadData];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.mapView showAnnotations:annArray animated:YES];
        self.needScroll = NO;
        [self playAndChangeSpotAnnViewWith:0 needPlay:NO];
    });
   
    
    if (self.pageType != 1) {
        
        __block LineModel *currentlineModel = nil;
        [DownloadListDAO getLineModelWithUnionid:self.lineModel.unionid Block:^(LineModel *lineModel) {
            currentlineModel = lineModel;
        }];
        
        if (!currentlineModel) {
            
            return;
        }
    }
    
    CGFloat progress;
    DownloadState state = [[DownloadManager sharedManager] downloadSateForModel:self.lineModel progress:&progress];
    
    if (state == DownloadStateCompleted || state == DownloadStateFailed) {
        self.lineModel.state = state;
    }
    
    self.lineModel.progress = progress;
    self.lineModel.state = self.lineModel.state;
    
    self.playBar.downloadState = self.lineModel.state;
    self.playBar.downloadProgress = progress;
}

# pragma mark  - 问问题

#pragma mark -MKMapViewDelegate
- (nullable MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation {
    
    if ([annotation isKindOfClass:[IGAnnotation class]]) {
        
        static NSString *customViewID = @"customView";
        
        SpotAnnView *customView = (SpotAnnView *)[mapView dequeueReusableAnnotationViewWithIdentifier:customViewID];
        if (!customView){
            
            customView = [[SpotAnnView alloc] initWithAnnotation:annotation reuseIdentifier:customViewID];
            customView.delegate = self;
        }
        customView.annotation = annotation;
        
        if ([((IGAnnotation *)annotation).infos[IGAnnotationIndexKey] integerValue] == self.currentIndex) {
            
            [customView showCallView];
        } else {
            [customView hiddenCallView];
        }
        
        return customView;
    }
    return nil;//返回nil代表使用默认样式
}

//实现画线的代理方法
- (MKPolylineRenderer *)mapView:(MKMapView *)mapView viewForOverlay:(id<MKOverlay>)overlay{
    
    if ([overlay isKindOfClass:[MKPolyline class]]) {
        
        MKPolylineRenderer *line = [[MKPolylineRenderer alloc] initWithOverlay:overlay];
        line.strokeColor = kThemeColor;
        line.lineWidth = 5.0f;
        return line;
    }
    return nil;
}

#pragma mark -IGAnnotationViewDelegatge
- (void)annotationClickView:(SpotAnnView *)annView {
    
    IGAnnotation *ann = (IGAnnotation *)annView.annotation;
    
    NSInteger currentIndex = [ann.infos[IGAnnotationIndexKey] integerValue];
    
    [self playAndChangeSpotAnnViewWith:currentIndex needPlay:YES];
}

- (void)distanceLine:(IGAnnotation *)ann NeedPlay:(BOOL)play {
    
    if (!ann) {
        return;
    }
    
    CGFloat distance = [IGUtils getDistanceFromCoordinate:ann.coordinate toCoordinate:transformFromWGSToGCJ( [LocationManager sharedManager].currentLocation.coordinate, self.lineModel.country)];
    
    [self selectScenicPointWith:[ann.infos[IGAnnotationIndexKey] integerValue] withIsPlay:play];
    
    if (distance < 3000 && self.lineModel.transport.integerValue <= 1) { //画线
        
        self.hasDrawedLine = YES;
        
        [self addLineTo:ann.coordinate];
        
    } else {
        
        self.hasDrawedLine = NO;
    }
    [self resetMapCenter:ann];
}


#pragma mark - 音频切换

- (void)changeRecordPointWith:(NSInteger)state isAutomatic:(BOOL)isAutomatic{
    
    NSInteger index = self.currentIndex + state;
    NSInteger total = self.viewsArray.count;
    
    if (index >= total ) {
        
        
        if (!isAutomatic) {
            [IGUtils showToast:MYLocalizedString(@"SITEPLAY_LAST_ONE", nil)];
        }
        return;
    }
    
    if (index < 0 ) {
        
        [IGUtils showToast:MYLocalizedString(@"SITEPLAY_FIRST_ONE", nil)];
        return;
    }
    
    [self playAndChangeSpotAnnViewWith:index needPlay:YES];
    
    [MobClick event:@"4_0_2"];
}

- (void)playAndChangeSpotAnnViewWith:(NSInteger)tag needPlay:(BOOL)play {
    
    
    if (self.annArray.count <= tag) {
        return;
    }
    
    IGAnnotation *currentAnn = self.annArray[tag];
    
    
    if (tag != self.currentIndex) {
        
        if ( self.currentIndex < self.annArray.count && self.currentIndex  >= 0) {
            SpotAnnView *annView = (SpotAnnView *)[self.mapView viewForAnnotation:self.annArray[self.currentIndex]];
            
            if ([annView isKindOfClass:[SpotAnnView class]]) {
                
                [annView hiddenCallView];
            }
        }
        
        [self distanceLine:currentAnn NeedPlay:play];
    }
    
    self.currentIndex = tag;
    
    SpotAnnView *annView = (SpotAnnView *)[self.mapView viewForAnnotation:currentAnn];
    if ([annView isKindOfClass:[SpotAnnView class]]) {
        
        [annView showCallView];
    }
}

- (void)selectScenicPointWith:(NSInteger)index withIsPlay:(BOOL)isPlay{
    
    ScenicPoint *scenicPoint = self.viewsArray[index];
    
    self.currentScenicPoint = scenicPoint;
    
    if (self.currentIndex != index) {
        CityTourLinePointCell * cell = (CityTourLinePointCell *)[self.lineCollectionView cellForItemAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:self.currentIndex]];
        cell.select = NO;
    }
    
    NSIndexPath * indexPath = [NSIndexPath indexPathForRow:0 inSection:index];
    CityTourLinePointCell * currenCell = (CityTourLinePointCell *)[self.lineCollectionView cellForItemAtIndexPath:indexPath];
    currenCell.select = YES;
    
    if (self.needScroll) {
        [self.lineCollectionView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:YES];
    }
    
    self.needScroll = YES;
    
    self.scenicPointLabel.text = [NSString stringWithFormat:@"%ld.%@",index +1 ,self.currentScenicPoint.spotname];
    [self markStartOrEndLanelWith:index ScenicPoint:scenicPoint];
    self.cycleScrollView.imageURLStringsGroup = self.currentScenicPoint.pictureArray;
    [self.lineCollectionView reloadData];
    [self.playBar playMusicWithPlayPath:self.currentScenicPoint withIsPlay:isPlay];
}

- (void)markStartOrEndLanelWith:(NSInteger)index ScenicPoint:(ScenicPoint *)point {
    
    if (point.linkviewid.length > 0) {
        
        self.startOrEndBg.hidden = NO;
        self.startOrEndLabel.hidden = YES;
        self.scenicPointLabel.textColor =  kThemeColor;
        self.startOrEndBg.userInteractionEnabled = YES;
        self.scenicPointLabel.userInteractionEnabled = YES;
        self.startOrEndBg.image = [UIImage imageNamed:@"link"];
        self.scenicPointLabel.frame = CGRectMake(46, 20, self.popView.frame.size.width - 140, 30);
    }else if (index == 0) {
        self.startOrEndLabel.hidden = NO;
        self.startOrEndLabel.backgroundColor = kThemeColor;
        self.startOrEndLabel.text = MYLocalizedString(@"CITYTOUR_START", nil);
        self.scenicPointLabel.frame = CGRectMake(46, 20, self.popView.frame.size.width - 140, 30);
    }else if (index == self.viewsArray.count - 1) {
        self.startOrEndLabel.hidden = NO;
        self.startOrEndLabel.text = MYLocalizedString(@"CITYTOUR_end", nil);
        self.startOrEndLabel.backgroundColor = kThemeRedColor;
        self.scenicPointLabel.frame = CGRectMake(46, 20, self.popView.frame.size.width - 140, 30);
    }else {
        if (!self.startOrEndLabel.hidden) {
            self.startOrEndLabel.hidden = YES;
            self.scenicPointLabel.frame = CGRectMake(16, 20, self.popView.frame.size.width - 140, 30);
        }
        if (!self.startOrEndBg.hidden) {
            self.startOrEndBg.hidden = YES;
            self.scenicPointLabel.frame = CGRectMake(16, 20, self.popView.frame.size.width - 140, 30);
        }
        
        self.scenicPointLabel.textColor = kSubitleColor  ;
        self.startOrEndBg.userInteractionEnabled = NO;
        self.scenicPointLabel.userInteractionEnabled = NO;
    }
    
}
#pragma mark  scrollImageView

- (UIView *)popView {
    
    if (!_popView) {
        _popView = [[UIView alloc] initWithFrame:CGRectMake(8,SCREEN_HEIGHT - (PopViewH + self.toBottomSpace.constant + 8), SCREEN_WIDTH - 16,PopViewH)];
        _popView.backgroundColor = [UIColor whiteColor];
        _popView.clipsToBounds = YES;
        [self.view addSubview:_popView];
        _upOrDownBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _upOrDownBtn.frame = CGRectMake(10,0, SCREEN_WIDTH - 50, 20);
        [_upOrDownBtn setImage:[UIImage imageNamed:@"unfold"] forState:UIControlStateNormal];
        _upOrDownBtn.imageView.contentMode = UIViewContentModeScaleAspectFit;
        [_upOrDownBtn addTarget:self action:@selector(upOrDownBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
        
        [self.popView addSubview:_upOrDownBtn];
        
        
        _startOrEndLabel = [[UILabel alloc] initWithFrame:CGRectMake(16, 22.5, 25, 25)];
        _startOrEndBg = [[UIImageView alloc] initWithFrame:CGRectMake(16, 22.5, 25, 25)];
        [self.popView addSubview:_startOrEndBg];
        _startOrEndLabel.layer.cornerRadius = 12.5;
        _startOrEndLabel.clipsToBounds = YES;
        _startOrEndLabel.textColor = [UIColor whiteColor];
        _startOrEndLabel.text = MYLocalizedString(@"CITYTOUR_START", nil);
        _startOrEndLabel.font = Font(14);
        _startOrEndLabel.textAlignment = NSTextAlignmentCenter;
       // _startOrEndBg.image = [UIImage imageNamed:@"lines_location_began"];
        [self.popView addSubview:_startOrEndLabel];
        
        _scenicPointLabel = [[UILabel alloc] initWithFrame:CGRectMake(46, 20, self.popView.frame.size.width - 140, 30)];
        _scenicPointLabel.font = Font(16);
        _scenicPointLabel.textColor = kSubitleColor;
        _scenicPointLabel.adjustsFontSizeToFitWidth = YES;
        _scenicPointLabel.minimumScaleFactor = 0.6;
        [self.popView addSubview:_scenicPointLabel];
        
        UITapGestureRecognizer * tap1 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(goRelateSCenicVC:)];
        
        UITapGestureRecognizer * tap2 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(goRelateSCenicVC:)];
        [_startOrEndBg addGestureRecognizer:tap1];
        [_scenicPointLabel addGestureRecognizer:tap2];
        
        _guideBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _guideBtn.frame = CGRectMake(self.popView.frame.size.width - 92, 20, 30, 30);
        [_guideBtn setImage:[UIImage imageNamed:@"lines_gps"] forState:UIControlStateNormal];
        [_guideBtn addTarget:self action:@selector(guideLine:) forControlEvents:UIControlEventTouchUpInside];
        [self.popView addSubview:_guideBtn];
        
        _currentLocationBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _currentLocationBtn.frame = CGRectMake(self.popView.frame.size.width - 46, 20, 30, 30);
        [_currentLocationBtn setImage:[UIImage imageNamed:@"lines_location"] forState:UIControlStateNormal];
        [_currentLocationBtn addTarget:self action:@selector(showCurrentLocation:) forControlEvents:UIControlEventTouchUpInside];
        [self.popView addSubview:_currentLocationBtn];
        
        _cycleScrollView = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(16, 60,self.popView.frame.size.width - 32, self.popView.frame.size.width - 32) delegate:nil placeholderImage:[UIImage imageNamed:@"placeholder_squ"]];
        _cycleScrollView.bannerImageViewContentMode = UIViewContentModeScaleAspectFill;
        [self.popView addSubview:_cycleScrollView];
        
        UICollectionViewFlowLayout * layout = [[UICollectionViewFlowLayout alloc] init];
        layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        self.lineCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(16,self.popView.frame.size.width + 40,self.popView.frame.size.width - 32, 105) collectionViewLayout:layout];
        
        self.lineCollectionView.backgroundColor = [UIColor whiteColor];
        self.lineCollectionView.delegate = self;
        self.lineCollectionView.dataSource = self;
        [self.popView addSubview:self.lineCollectionView];
        self.lineCollectionView.showsHorizontalScrollIndicator = NO;
        [self.lineCollectionView registerNib:[UINib nibWithNibName:@"CityTourLinePointCell" bundle:nil] forCellWithReuseIdentifier:@"CityTourLinePointCell"];
        [self.lineCollectionView  registerNib:[UINib nibWithNibName:@"TransportHeaderView" bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"TransportHeaderView"];
        
        [self.popView addGestureRecognizer:[[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panPopView:)]];
    }
    
    self.view.backgroundColor = kBGColor;
    return _popView;
}

-(void)goRelateSCenicVC:(UITapGestureRecognizer *)tap {
    
    ScenicDescribeVC *scenicDesVC = [ScenicDescribeVC new];
    Scenic * scenic = [[Scenic alloc] init];
    scenic.ID = self.currentScenicPoint.linkviewid;
    scenicDesVC.scenic = scenic;
    [self.navigationController pushViewController:scenicDesVC animated:YES];
}
//- (void)commentClicked:(UIButton *)btn {
//
//    [MobClick event:@"4_0_12"];
//
//    if (self.lineModel.bought) {
//        RatingVC *rateVC = [RatingVC new];
//        if (self.lineModel.hasscore.integerValue >0) {
//            rateVC.hasscore = self.lineModel.hasscore.integerValue;
//            rateVC.comment = self.lineModel.comment;
//        }
//
//        [rateVC show:self completeBlock:^(CGFloat score, NSString *comment) {
//
//            [NetAPIManager evaluate:self.lineModel.lineid score:@(score) comment:comment Block:^(NSString *result, NSError *error) {
//
//                if (!error) {
//                    self.lineModel.hasscore =@(score).stringValue;
//                    self.lineModel.comment = comment;
//                    [IGUtils showToast:@"评价成功"];
//                }
//            }];
//        }];
//    }
//}
- (void)guideLine:(UIButton *)btn {
    
    CLLocationCoordinate2D coordinate = CLLocationCoordinate2DMake(self.currentScenicPoint.lat.doubleValue, self.currentScenicPoint.lng.doubleValue);
    [IGUtils tractficToLocation:transformFromWGSToGCJ(coordinate, self.lineModel.country) vc:self];
    [MobClick event:@"4_0_9"];
}

- (void)showCurrentLocation:(UIButton *)btn {
    
    if (self.popView.frame.size.height > 60) {
        
        CGRect popFrame = self.popView.frame;
        popFrame.origin.y = SCREEN_HEIGHT - (PopViewH + self.toBottomSpace.constant + 8);
        popFrame.size.height = 60;
        CGRect mapRect = self.mapView.frame;
        mapRect.origin.y = (popFrame.origin.y - (SCREEN_HEIGHT - (PopViewH + self.toBottomSpace.constant + 8))) / 2.0f ;
        self.upOrDownBtn.selected = NO;
        @weakify(self);
        [UIView animateWithDuration:0.25 animations:^{
            @strongify(self);
            self.popView.frame = popFrame;
            self.mapView.frame = mapRect;
        }];
    }
    
    if (self.currentIndex < self.annArray.count) {
        
        IGAnnotation *ann = self.annArray[self.currentIndex];
        
        if (ann) {
            [self resetMapCenter:ann];
        }
    }
    
    
    
    [MobClick event:@"4_0_10"];
}

- (void)resetMapCenter:(IGAnnotation *)ann {
    
    if (self.hasDrawedLine) {
        
        [self.mapView setUserTrackingMode:MKUserTrackingModeFollowWithHeading animated:YES];
        
        return;
    }
    
    [self.mapView setUserTrackingMode:MKUserTrackingModeNone animated:YES];
    
    CLLocationCoordinate2D center = ann.coordinate;
    
    if ((center.latitude >= -90) && (center.latitude <= 90) && (center.longitude >= -180) && (center.longitude <= 180)) {
        
        MKCoordinateSpan span = self.mapView.region.span;
        [self.mapView setRegion:MKCoordinateRegionMake(center, span) animated:YES];
    }
}



- (void)panPopView:(UIPanGestureRecognizer *)pan {
    
    //    CGPoint panPoint = [pan locationInView:self.view];
    CGPoint distance = [pan translationInView:self.view];
    
    CGRect popFrame = self.popView.frame;
    popFrame.origin.y += distance.y - self.lastDistance;
    popFrame.size.height += self.lastDistance - distance.y;
    
    if (popFrame.origin.y < (SCREEN_HEIGHT - SCREEN_WIDTH - 141 - self.toBottomSpace.constant - 8)) {
        popFrame.origin.y = SCREEN_HEIGHT - SCREEN_WIDTH - 141 - self.toBottomSpace.constant - 8;
        
        
        popFrame.size.height = SCREEN_WIDTH + 141;
        [self off];
    }
    
    if (popFrame.origin.y > (SCREEN_HEIGHT - (PopViewH + self.toBottomSpace.constant + 8))) {
        
        popFrame.origin.y = SCREEN_HEIGHT - (PopViewH + self.toBottomSpace.constant + 8);
        
        popFrame.size.height = 60;
        [self open];
    }
    self.popView.frame = popFrame;
    
    self.lastDistance = distance.y;
    
    CGRect mapRect = self.mapView.frame;
    
    mapRect.origin.y = (popFrame.origin.y - (SCREEN_HEIGHT - (PopViewH + self.toBottomSpace.constant + 8))) / 2.0f ;
    
    self.mapView.frame = mapRect;
    
    
    if (pan.state == UIGestureRecognizerStateEnded) {
        
        if (distance.y > 0 ) {
            popFrame.origin.y = SCREEN_HEIGHT - (PopViewH + self.toBottomSpace.constant + 8);
            popFrame.size.height = 60;
            [self open];
            
        } else {
            popFrame.origin.y = SCREEN_HEIGHT - SCREEN_WIDTH - 141 - self.toBottomSpace.constant - 8;
            popFrame.size.height = SCREEN_WIDTH + 141;
            [self off];
        }
        
        CGRect mapRect = self.mapView.frame;
        
        mapRect.origin.y = (popFrame.origin.y - (SCREEN_HEIGHT - (PopViewH + self.toBottomSpace.constant + 8))) / 2.0f ;
        
        @weakify(self);
        [UIView animateWithDuration:0.25 animations:^{
            @strongify(self);
            self.popView.frame = popFrame;
            self.mapView.frame = mapRect;
        } completion:^(BOOL finished) {
            self.upOrDownBtn.selected = !self.upOrDownBtn.selected;
            self.lastDistance = 0;
        }];
    }
}

- (void)upOrDownBtnClicked:(UIButton *)sender {
    
    CGRect popFrame = self.popView.frame;
    if (sender.selected) {
        popFrame.origin.y = SCREEN_HEIGHT - (PopViewH + self.toBottomSpace.constant + 8);
        popFrame.size.height = 60;
        [self open];
        [MobClick event:@"4_0_3"];
        
    } else {
        [MobClick event:@"4_0_1"];
        popFrame.origin.y = SCREEN_HEIGHT - SCREEN_WIDTH - 141 - self.toBottomSpace.constant - 8;
        popFrame.size.height = SCREEN_WIDTH + 141;
        [self off];
    }
    
    CGRect mapRect = self.mapView.frame;
    
    mapRect.origin.y = (popFrame.origin.y - (SCREEN_HEIGHT - (PopViewH + self.toBottomSpace.constant + 8))) / 2.0f ;
    
    @weakify(self);
    [UIView animateWithDuration:0.25 animations:^{
        @strongify(self);
        self.popView.frame = popFrame;
        self.mapView.frame = mapRect;
    }];
    sender.selected = !sender.selected;
}



#pragma PaymentPageVCDelegate  UICollectionViewDataSource

- (NSInteger) collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    
    return 1;
    
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    
    return self.viewsArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    CityTourLinePointCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"CityTourLinePointCell" forIndexPath:indexPath];
    //    cell.indexLabel.text = [NSString stringWithFormat:@"%ld",indexPath.section + 1];
    cell.select = NO;
    
    ScenicPoint * model = self.viewsArray[indexPath.section];
    [cell setPlayCellData:model];
    
    if (self.currentIndex == indexPath.section) {
        cell.select = YES;
        cell.record = NO;
    }
    return cell;
}


- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    
    if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
        
        TransportHeaderView * headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"TransportHeaderView" forIndexPath:indexPath];
        ScenicPoint * model = self.viewsArray[indexPath.section];
        
        headerView.transport = model.transport.integerValue;
        
        return headerView;
    }
    
    return nil;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    return CGSizeMake(70, 105);
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {
    
    if (section == 0) {
        return CGSizeZero;
    }
    
    return CGSizeMake(35, 105);
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section == self.currentIndex) {
        return;
    }
    //    [self changeRecordPointWith:indexPath.section];
    
    [self playAndChangeSpotAnnViewWith:indexPath.section needPlay:YES];
    [MobClick event:@"4_0_4"];
}

@end
